<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "order".
 *
 * @property int $id
 * @property string $order_no 订单编号
 * @property int $region_1 一级地域ID
 * @property int $region_2 二级地域ID
 * @property int $region_3 三级地域ID
 * @property string $price 价格
 * @property string $install_price 安装制作价格
 * @property string $total_price 总计金额
 * @property int $buyer_id 买家ID
 * @property string $buyer 买家名称
 * @property int $status 订单状态，0:待支付,1:已支付,2申请退款中,3:交易取消，4:交易完成
 * @property int $invitor_id 邀请人ID
 * @property int $addtime 添加时间
 */
class Order extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'order';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'order_no', 'price', 'buyer_id', 'buyer', 'status', 'addtime'], 'required'],
            [['id', 'order_no', 'region_1', 'buyer_id', 'invitor_id', 'addtime'], 'integer'],
            [['price'], 'number'],
            [['buyer'], 'string', 'max' => 100],
            [['status'], 'string', 'max' => 3],
            [['order_no'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'order_no' => '订单编号',
            'region_id' => '地区ID',
            'price' => '价格',
            'buyer_id' => '买家ID',
            'buyer' => '买家名称',
            'status' => '订单状态，0:待支付,1:已支付,2申请退款中,3:交易取消，4:交易完成',
            'invitor_id' => '邀请人ID',
            'addtime' => '添加时间',
        ];
    }
    
    public static function createOrder($userid,$username,$invitor_id,$goods_info){
        //生成一个订单编号
        $order_no = Tools::build_order_no($userid);
        
        //判断是否有营销合伙人介入
        $roleid = \common\models\SysUser2role::getUserRoleId($invitor_id);
        $invitor_id = $roleid == 5 ? $invitor_id : 0;
        //设置订单初始价格
        $order_price = 0;
        $order_install_price = 0;
        
        //订单相关数据处理开始
        $transaction = Yii::$app->db->beginTransaction();
        
        try {
            foreach($goods_info as $order_goods){
                $goods_id = $order_goods[0];
                $goods_have_package = $order_goods[1];
                if($goods_have_package == 0){
                    $nums = $order_goods[2];
                }else{
                    $goods_package_info = $order_goods[2];
                }

                $goods = Goods::findOne($goods_id);

                if($goods->first_cate==1 && $goods->have_package==0 && $nums<3){
                    throw new \Exception('广告位商品必须购买至少3个月！');
                }

                if($goods->seller_id == $userid){
                    throw new \Exception('不能购买自己发布的商品！');
                }

                if($goods->have_package == 1 && $goods_package_info == ""){
                    throw new \Exception('请选择套餐内容！');
                }

                //不含套餐的商品加入订单
                if($goods->have_package == 0){
                    //广告位商品，检测是否能够购买
                    if($goods->first_cate==1){
                        if($goods->order_endtime < time() || $goods->last_buyerid == $userid){
                        //符合条件，可加入订单数据
                        }else{
                            throw new \Exception('商品暂时不能购买，请等待上次购买到期再来！');
                        }
                    }
                    //设备商品，检测购买条件
                    if($goods->first_cate == 7){
                        if($goods->nums >= $nums){
                            //符合条件，可加入订单数据
                        }else{
                            throw new \Exception($goods->name.'库存不足！');
                        }
                    }

                    //符合购买条件，加入订单
                    $order_goods_model = new OrderGoods();
                    $order_goods_model->order_no = $order_no;
                    $order_goods_model->goods_id = $goods->id;
                    $order_goods_model->goods_no = $goods->goods_no;
                    $order_goods_model->goods_name = $goods->name;
                    $order_goods_model->first_cate = $goods->first_cate;
                    $order_goods_model->second_cate = $goods->second_cate;
                    $order_goods_model->third_cate = $goods->third_cate;
                    $order_goods_model->have_package = $goods->have_package;
                    $order_goods_model->seller_id = $goods->seller_id;
                    $order_goods_model->seller = $goods->seller;
                    $order_goods_model->buyer_id = $userid;
                    $order_goods_model->buyer = $username;
                    $order_goods_model->nums = $nums;
                    $order_goods_model->status = 0;
                    $order_goods_model->invitor_id = $invitor_id;
                    $order_goods_model->install_price = $nums*$goods->install_price;
                    $order_goods_model->price = $nums*$goods->price;
                    $order_goods_model->price_total = $nums*($goods->price+$goods->install_price);
                    $order_goods_model->region_1 = $goods->region_1;
                    $order_goods_model->region_2 = $goods->region_2;
                    $order_goods_model->region_3 = $goods->region_3;
                    if($goods->first_cate == 1){
                        $order_goods_model->time_begin = $goods->order_endtime;
                        $order_goods_model->time_end = $goods->order_endtime + $nums*3600*24*30;
                    }
                    $order_goods_model->addtime = time();

                    $order_price += $nums * $goods->price;
                    $order_install_price += $nums * $goods->install_price;

                    if (!$order_goods_model->save(false)) {
                        \Yii::getLogger()->log($order_goods_model->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('订单商品添加失败！');
                    }
                }
                //含套餐的商品加入购物车
                if($goods->have_package == 1){
                    $price = 0;
                    $price_total = 0;
                    $install_price = 0;
                    $packages = explode(';', $goods_package_info);
                    
                    foreach($packages as $package){
                        if(empty($package)){continue;}
                        $package_one = explode(',', $package);
                        $package_id = $package_one[0];
                        $package_buy_num = $package_one[1];
                        $package_model = GoodsPackage::findOne($package_id);
                        $price += $package_buy_num*$package_model->price;
                        $install_price += $package_buy_num*$package_model->install_price;
                        $price_total += ($package_model->price+$package_model->install_price)*$package_buy_num;

                        switch($goods->first_cate){
                            case 1://广告位商品，检测是否能够购买
                                if($package_model->buy_able_time < time() || $package_model->last_buyerid == $userid){
                                    //符合条件
                                }else{
                                    throw new \Exception("套餐【$package_model->name】暂时不能购买，请等待上次购买到期再来！");
                                }
                                break;
                            case 7://设备商品，检测套餐 库存是否符合
                                if($package_model->nums >= $package_buy_num){
                                    //符合条件
                                }else{
                                    throw new \Exception("套餐【$package_model->name】库存不足！");
                                }
                                break;
                            default:
                                //do nothing
                        }
                        //保存订单套餐数据
                        $order_goods_package_model = new OrderGoodsPackage();
                        $order_goods_package_model->order_no = $order_no;
                        $order_goods_package_model->goods_id = $goods->id;
                        $order_goods_package_model->goods_no = $goods->goods_no;
                        $order_goods_package_model->first_cate = $goods->first_cate;
                        $order_goods_package_model->package_id = $package_id;
                        $order_goods_package_model->package_name = $package_model->name;
                        $order_goods_package_model->install_price = $package_model->install_price;
                        $order_goods_package_model->price_one = $package_model->price;
                        $order_goods_package_model->price_total = $package_buy_num*$package_model->price;
                        
                        if($goods->first_cate == 1){
                            $order_goods_package_model->begin_time = $package_model->buy_able_time;
                            $order_goods_package_model->end_time = $package_model->buy_able_time + 3600*24*30*$package_buy_num;
                        }

                        $order_goods_package_model->nums = $package_buy_num;
                        $order_goods_package_model->addtime = time();

                        $order_price += $package_buy_num * $package_model->price;
                        $order_install_price += $package_buy_num * $package_model->install_price;

                        if (!$order_goods_package_model->save(false)) {
                            //\Yii::getLogger()->log($order_goods_package_model->errors, \yii\log\Logger::LEVEL_ERROR);
                            throw new \Exception('订单商品套餐添加失败！');
                        }
                    }

                    //保存含有套餐的订单商品数据
                    $order_goods_model = new OrderGoods();
                    $order_goods_model->order_no = $order_no;
                    $order_goods_model->goods_id = $goods->id;
                    $order_goods_model->goods_no = $goods->goods_no;
                    $order_goods_model->goods_name = $goods->name;
                    $order_goods_model->first_cate = $goods->first_cate;
                    $order_goods_model->second_cate = $goods->second_cate;
                    $order_goods_model->third_cate = $goods->third_cate;
                    $order_goods_model->have_package = $goods->have_package;
                    $order_goods_model->seller_id = $goods->seller_id;
                    $order_goods_model->seller = $goods->seller;
                    $order_goods_model->buyer_id = $userid;
                    $order_goods_model->buyer = $username;
                    $order_goods_model->nums = 0;
                    $order_goods_model->status = 0;
                    $order_goods_model->invitor_id = $invitor_id;
                    $order_goods_model->install_price = $install_price;
                    $order_goods_model->price = $price;
                    $order_goods_model->price_total = $price_total;
                    $order_goods_model->region_1 = $goods->region_1;
                    $order_goods_model->region_2 = $goods->region_2;
                    $order_goods_model->region_3 = $goods->region_3;
                    $order_goods_model->addtime = time();
                    
                    if (!$order_goods_model->save(false)) {
                        \Yii::getLogger()->log($order_goods_model->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('订单商品(套餐商品)添加失败！');
                    }
                }
            }
            //商品检测完毕，开始生成订单表数据
            $order = new Order();
            $order->order_no = $order_no;
            $order->region_1 = $goods->region_1;
            $order->region_2 = $goods->region_2;
            $order->region_3 = $goods->region_3;
            $order->price = $order_price;
            $order->install_price = $order_install_price;
            $order->total_price = $order_price+$order_install_price;
            $order->buyer_id = $userid;
            $order->buyer = $username;
            $order->status = 0;
            $order->invitor_id = $invitor_id;
            $order->addtime = time();
            if (!$order->save(false)) {
                \Yii::getLogger()->log($order->errors, \yii\log\Logger::LEVEL_ERROR);
                throw new \Exception('订单添加失败！');
            }
            
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            
            $output['success'] = 0;
            $output['msg'] = $e->getMessage();
            Tools::outputjson($output);
        }
        //订单相关数据处理结束
        return $order_no;
    }
    
    //订单商品检测
    public static function orderCheck($order_no){
        $order = Order::findOne(['order_no'=>$order_no]);
        $buyer_id = $order->buyer_id;
        //获取不含套餐的商品
        $no_pack_order_goods_data = OrderGoods::getNoPackageGoodsByOrderNo($order_no);        
        if(!empty($no_pack_order_goods_data)){
            foreach($no_pack_order_goods_data as $no_pack_order_goods){
                $goods = Goods::findOne($no_pack_order_goods['goods_id']);
                if($no_pack_order_goods['first_cate']==1){//广告位商品
                    if($goods->order_endtime < time() || $goods->last_buyerid == $buyer_id){
                        //符合购买条件
                    }else{
                        return false;
                    }
                }
                if($no_pack_order_goods['first_cate']==7){//设备类型的商品
                    if($goods->nums >= $no_pack_order_goods['nums']){
                        //符合条件
                    }else{
                        return false;
                    }
                }
            }
        }
        
        //检测套餐
        $order_goods_packages = OrderGoodsPackage::getPackageByOrderNo($order_no);
        
        foreach($order_goods_packages as $order_goods_package){
            $goodsPack = GoodsPackage::findOne($order_goods_package['package_id']);
            if($order_goods_package['first_cate'] == 1){//广告位套餐
                
                if($goodsPack->buy_able_time < time() || $goodsPack->last_buyerid == $buyer_id){
                    //符合条件
                }else{
                    return false;
                }
            }
            if($order_goods_package['first_cate'] == 7){//设备套餐
                if($goodsPack->nums >= $order_goods_package['nums']){
                    //符合条件
                }else{
                    return false;
                }
            }
        }
        return true;
    }
    /***
     * 订单回调处理
     * $order_no 订单编号
     * $pay_no 在线支付流水号
     */
    public static function paybackDeal($order_no,$pay_no=''){
        $sys_rate = SysRate::getSysRate();
        $order = Order::findOne(['order_no'=>$order_no]);
        $userid = $order->buyer_id;
        $total_money = $order->total_price;
        $region = Region::findOne($order->region_3);
        
        $order_check = self::orderCheck($order_no);
        
        $transaction = Yii::$app->db->beginTransaction();
        try{
            if($pay_no != ""){
                //支付金额写入资金记录begin
                $user_fund_detail_model = new UserFundDetail();
                $user_fund_detail_model->userid = $userid;
                $user_fund_detail_model->type = 0;
                $user_fund_detail_model->money = $total_money;
                $user_fund_detail_model->pay_no = $pay_no;
                $user_fund_detail_model->name = '在线支付';
                $user_fund_detail_model->addtime = time();
                if (!$user_fund_detail_model->save(false)) {
                    \Yii::getLogger()->log($user_fund_detail_model->errors, \yii\log\Logger::LEVEL_ERROR);
                    throw new \Exception('生成充值记录错误！');
                }//支付金额写入资金记录end
            }
            
            //检测商品购买条件
            if($order_check){//符合购买条件，买家购买资金记录，改变商品库存信息 , 设置广告位商品 能购买的时间点 以及上次购买的人
                //买家购买资金支出记录
                $user_fund_detail_buy_model = new UserFundDetail();
                $user_fund_detail_buy_model->userid = $userid;
                $user_fund_detail_buy_model->type = 1;
                $user_fund_detail_buy_model->money = -$total_money;
                $user_fund_detail_buy_model->order_no = $order_no;
                $user_fund_detail_buy_model->name = '购买商品，支付订单';
                $user_fund_detail_buy_model->addtime = time();
                if (!$user_fund_detail_buy_model->save(false)) {
                    \Yii::getLogger()->log($user_fund_detail_buy_model->errors, \yii\log\Logger::LEVEL_ERROR);
                    throw new \Exception('生成充值记录错误！');
                }
                
                $order_goods_arr = OrderGoods::getOrderGoodsByOrderNo($order_no);
                foreach($order_goods_arr as $order_goods){
                    $seller_in = $order_goods['price']*((100-$sys_rate['ad_rate'])/100);//卖家收入
                    
                    if($order_goods['first_cate']==1){//广告位商品
                        if($order_goods['have_package']==0){//不含套餐的广告位商品
                            //更新商品的购买信息
                            $update_goods_nums = Goods::updateAll(['order_endtime'=>$order_goods['time_end'],'last_buyerid'=>$userid],['id'=>$order_goods['goods_id']]);
                            if($update_goods_nums==0){
                                throw new \Exception('更新商品【广告位】失败！');
                            }
                        }else{//含套餐的广告位商品
                            $order_goods_package_arr = OrderGoodsPackage::getOrderGoodsPackage($order_no,$order_goods['goods_id']);
                            foreach($order_goods_package_arr as $order_goods_package){
                                $update_goods_pack_nums = GoodsPackage::updateAll(['buy_able_time'=>$order_goods_package['end_time'],'last_buyerid'=>$userid], ['id'=>$order_goods_package['package_id']]);
                                if($update_goods_pack_nums==0){
                                    throw new \Exception('更新商品库存【套餐广告位】失败！');
                                }
                            }
                        }
                    }
                    
                    if($order_goods['first_cate']==7){//设备商品
                        if($order_goods['have_package']==0){//不含套餐的设备商品
                            //更新商品的购买信息
                            $goods_model = Goods::findOne($order_goods['goods_id']);
                            $goods_model->nums = $goods_model->nums - $order_goods['nums'];
                            if (!$goods_model->save(false)) {
                                throw new \Exception('更新商品【不含套餐】库存错误！');
                            }
                        }else{//含套餐的广告位商品
                            $order_goods_package_arr = OrderGoodsPackage::getOrderGoodsPackage($order_no,$order_goods['goods_id']);
                            foreach($order_goods_package_arr as $order_goods_package){
                                
                                $goods_package_model = GoodsPackage::findOne($order_goods_package['package_id']);
                                $goods_package_model->nums = $goods_package_model->nums - $order_goods_package['nums'];
                                if (!$goods_package_model->save(false)) {
                                    throw new \Exception('更新商品【含套餐】库存错误！');
                                }
                            }
                        }
                    }
                    
                    //更新卖家资金，广告位商品的资金直接到账，其他类型的资金不做处理
                    if($order_goods['first_cate'] == 1){
                        $seller_in = $order_goods['price']*(100-$sys_rate['ad_rate'])/100;//卖家收入
                        $sys_fee = ($order_goods['price']-$seller_in);//系统费用
                        $agent_in = $region->agent_uid != 0 ? $sys_rate['agent_rate']*$sys_fee/100 : 0;
                        $inviter_in = $order->invitor_id !=0 ? $sys_rate['inviter_rate']*$sys_fee/100 : 0;
                        
                        $sys_in = $sys_fee - ($agent_in+$inviter_in);//系统收入
                        
                        if($region->agent_uid != 0){
                            //代理人资金记录
                            $agent_fund_detail_model = new UserFundDetail();
                            $agent_fund_detail_model->userid = $region->agent_uid;
                            $agent_fund_detail_model->type = 3;
                            $agent_fund_detail_model->money = $agent_in;
                            $agent_fund_detail_model->goods_id = $order_goods['goods_id'];
                            $agent_fund_detail_model->order_no = $order_no;
                            $agent_fund_detail_model->name = '广告位区域代理分成';
                            $agent_fund_detail_model->addtime = time();
                            if (!$agent_fund_detail_model->save(false)) {
                                \Yii::getLogger()->log($agent_fund_detail_model->errors, \yii\log\Logger::LEVEL_ERROR);
                                throw new \Exception('生成充值记录错误！');
                            }
                            //代理人资金
                            $agent_fund = UserFund::findOne(['userid'=>$region->agent_uid]);
                            if(empty($agent_fund)){//没有资金记录的，创建资金记录
                                $agent_fund_model = new UserFund();
                                $agent_fund_model->userid = $region->agent_uid;
                                $agent_fund_model->user_sum = $agent_in;
                                $agent_fund_model->addtime = time();
                                if (!$agent_fund_model->save(false)) {
                                    \Yii::getLogger()->log($agent_fund_model->errors, \yii\log\Logger::LEVEL_ERROR);
                                    throw new \Exception('生成用户资金记录错误！');
                                }
                            }else{
                                $agent_fund->user_sum = $agent_fund->user_sum + $agent_in;
                                if (!$agent_fund->save(false)) {
                                    \Yii::getLogger()->log($agent_fund->errors, \yii\log\Logger::LEVEL_ERROR);
                                    throw new \Exception('保存用户资金错误！');
                                }
                            }
                        }
                        
                        if($order->invitor_id !=0){
                            //合伙人资金记录
                            $partner_fund_detail_model = new UserFundDetail();
                            $partner_fund_detail_model->userid = $order->invitor_id;
                            $partner_fund_detail_model->type = 4;
                            $partner_fund_detail_model->money = $inviter_in;
                            $partner_fund_detail_model->goods_id = $order_goods['goods_id'];
                            $partner_fund_detail_model->order_no = $order_no;
                            $partner_fund_detail_model->name = '合伙人分成【广告位】';
                            $partner_fund_detail_model->addtime = time();
                            if (!$partner_fund_detail_model->save(false)) {
                                \Yii::getLogger()->log($partner_fund_detail_model->errors, \yii\log\Logger::LEVEL_ERROR);
                                throw new \Exception('生成充值记录错误！');
                            }
                            //合伙人资金
                            $partner_fund = UserFund::findOne(['userid'=>$order->invitor_id]);
                            if(empty($partner_fund)){//没有资金记录的，创建资金记录
                                $partner_fund_model = new UserFund();
                                $partner_fund_model->userid = $order->invitor_id;
                                $partner_fund_model->user_sum = $inviter_in;
                                $partner_fund_model->addtime = time();
                                if (!$partner_fund_model->save(false)) {
                                    \Yii::getLogger()->log($partner_fund_model->errors, \yii\log\Logger::LEVEL_ERROR);
                                    throw new \Exception('生成合伙人资金记录错误！');
                                }
                            }else{
                                $partner_fund->user_sum = $partner_fund->user_sum + $inviter_in;
                                if (!$partner_fund->save(false)) {
                                    \Yii::getLogger()->log($partner_fund->errors, \yii\log\Logger::LEVEL_ERROR);
                                    throw new \Exception('保存合伙人资金错误！');
                                }
                            }
                        }
                        
                        //添加系统资金记录
                        $sys_fund_detail_model = new SysFundDetail();
                        $sys_fund_detail_model->type = 0;
                        $sys_fund_detail_model->goods_id = $order_goods['goods_id'];
                        $sys_fund_detail_model->money = $sys_in;
                        $sys_fund_detail_model->order_no = $order_no;
                        $sys_fund_detail_model->addtime = time();
                        if (!$sys_fund_detail_model->save(false)) {
                            \Yii::getLogger()->log($sys_fund_detail_model->errors, \yii\log\Logger::LEVEL_ERROR);
                            throw new \Exception('生成系统资金记录错误！');
                        }
                        //更新系统资金
                        $sys_fund_model = SysFund::findOne(1);//获取系统资金
                        $sys_fund_model->sys_sum = $sys_fund_model->sys_sum + $sys_in;
                        if (!$sys_fund_model->save(false)) {
                            \Yii::getLogger()->log($sys_fund_model->errors, \yii\log\Logger::LEVEL_ERROR);
                            throw new \Exception('更新系统资金记录错误！');
                        }
                        
                        
                        //卖家资金记录
                        $seller_fund_detail_model = new UserFundDetail();
                        $seller_fund_detail_model->userid = $order_goods['seller_id'];
                        $seller_fund_detail_model->type = 2;
                        $seller_fund_detail_model->money = $seller_in;
                        $seller_fund_detail_model->name = '售出商品';
                        $seller_fund_detail_model->order_no = $order_no;
                        $seller_fund_detail_model->goods_id = $order_goods['goods_id'];
                        $seller_fund_detail_model->addtime = time();
                        if (!$seller_fund_detail_model->save(false)) {
                            \Yii::getLogger()->log($seller_fund_detail_model->errors, \yii\log\Logger::LEVEL_ERROR);
                            throw new \Exception('生成卖家资金记录错误！');
                        }
                        
                        $seller_fund = UserFund::findOne(['userid'=>$order_goods['seller_id']]);
                        if(empty($seller_fund)){//没有资金记录的，创建资金记录
                            $seller_fund_model = new UserFund();
                            $seller_fund_model->userid = $order_goods['seller_id'];
                            $seller_fund_model->user_sum = $seller_in;
                            $seller_fund_model->addtime = time();
                            if (!$seller_fund_model->save(false)) {
                                \Yii::getLogger()->log($seller_fund_model->errors, \yii\log\Logger::LEVEL_ERROR);
                                throw new \Exception('生成卖家资金错误！');
                            }
                        }else{
                            $seller_fund->user_sum = $seller_fund->user_sum + $inviter_in;
                            if (!$seller_fund->save(false)) {
                                \Yii::getLogger()->log($seller_fund->errors, \yii\log\Logger::LEVEL_ERROR);
                                throw new \Exception('保存卖家资金错误！');
                            }
                        }
                        
                        
                        
                    }
                    
                }
                //更新订单商品的信息 已支付
                $update_order_goods_nums = OrderGoods::updateAll(['status'=>1],['status'=>0,'order_no'=>$order_no]);
                if($update_order_goods_nums==0){
                    throw new \Exception('更新订单商品失败！');
                }
                
                //更新订单信息 已支付
                $update_order_nums = Order::updateAll(['status'=>1],['status'=>0,'order_no'=>$order_no]);
                if($update_order_nums==0){
                    throw new \Exception('更新订单失败！');
                }
                
                
                
                
            }else{//不符合购买条件，把支付金额加到用户的余额
                $user_fund = UserFund::findOne(['userid'=>$userid]);
                if(empty($user_fund)){//没有资金记录的，创建资金记录
                    $new_user_fund_model = new UserFund();
                    $new_user_fund_model->userid = $userid;
                    $new_user_fund_model->user_sum = $total_money;
                    $new_user_fund_model->addtime = time();
                    if (!$new_user_fund_model->save(false)) {
                        \Yii::getLogger()->log($new_user_fund_model->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('生成用户资金记录错误！');
                    }
                }else{
                    $user_fund->user_sum = $user_fund->user_sum + $total_money;
                    if (!$user_fund->save(false)) {
                        \Yii::getLogger()->log($user_fund->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('保存用户资金错误！');
                    }
                }
            }
            $transaction->commit();
        } catch (\yii\db\Exception $e){
            $transaction->rollBack();
            return $e->getMessage();
        }
        return 'success';
    }
    
    
    /***
     * 确认收货，资金处理
     */
    public static function orderConfirm($order_no){
        $order = Order::findOne(['order_no'=>$order_no]);
        $region = Region::findOne($order->region_3);
        $agent_uid = $region->agent_uid;
        //系统收费标准
        $sys_rate = SysRate::getSysRate();
        //获取订单的所有商品
        $order_goods_arr = OrderGoods::getOrderGoodsByOrderNo($order_no);
        foreach($order_goods_arr as $order_goods){
            $order_goods['id'];
            $order_goods['first_cate'];
            $order_goods['goods_id'];
            $order_goods['buyer_id'];
            $order_goods['seller_id'];
            $order_goods['have_package'];
            $order_goods['nums'];
            $order_goods['time_end'];
            $order_goods['invitor_id'];
            $order_goods['price'];
            $order_goods['install_price'];
            $order_goods['price_total'];
            //计算各个角色收入
            if($order_goods['first_cate'] == 1){//广告位类型的商品，确认收货时，处理安装制作对应的资金流记录
                $order_goods['install_price'];
                $seller_in = $order_goods['install_price']*(100-$sys_rate['ad_install_rate'])/100;//卖家收入
                $sys_fee = ($order_goods['install_price']-$seller_in);//系统费用
                $agent_in = $agent_uid != 0 ? $sys_rate['agent_rate']*$sys_fee/100 : 0;//区域代理商收入
                $inviter_in = $order_goods['invitor_id'] !=0 ? $sys_rate['inviter_rate']*$sys_fee/100 : 0;//合伙人收入
                $sys_in = $sys_fee - ($agent_in+$inviter_in);//系统收入
                $money_type_string = "安装制作";
            }
            if($order_goods['first_cate'] == 7){//设备类商品，确认收货时，处理商品资金的记录
                $seller_in = $order_goods['price_total']*(100-$sys_rate['device_rate'])/100;//卖家收入
                $sys_fee = ($order_goods['price_total']-$seller_in);//系统费用
                $agent_in = $agent_uid != 0 ? $sys_rate['agent_rate']*$sys_fee/100 : 0;//区域代理商收入
                $inviter_in = $order_goods['invitor_id'] !=0 ? $sys_rate['inviter_rate']*$sys_fee/100 : 0;//合伙人收入
                $sys_in = $sys_fee - ($agent_in+$inviter_in);//系统收入
                $money_type_string = "设备商品";
            }
            $transaction = Yii::$app->db->beginTransaction();
            try{
                //卖家资金记录
                $seller_fund_detail_model = new UserFundDetail();
                $seller_fund_detail_model->userid = $order_goods['seller_id'];
                $seller_fund_detail_model->type = 2;
                $seller_fund_detail_model->money = $seller_in;
                $seller_fund_detail_model->name = '售出商品--'.$money_type_string;
                $seller_fund_detail_model->order_no = $order_no;
                $seller_fund_detail_model->goods_id = $order_goods['goods_id'];
                $seller_fund_detail_model->addtime = time();
                if (!$seller_fund_detail_model->save(false)) {
                    \Yii::getLogger()->log($seller_fund_detail_model->errors, \yii\log\Logger::LEVEL_ERROR);
                    throw new \Exception('生成卖家资金记录错误！');
                }

                $seller_fund = UserFund::findOne(['userid'=>$order_goods['seller_id']]);
                if(empty($seller_fund)){//没有资金记录的，创建资金记录
                    $seller_fund_model = new UserFund();
                    $seller_fund_model->userid = $order_goods['seller_id'];
                    $seller_fund_model->user_sum = $seller_in;
                    $seller_fund_model->addtime = time();
                    if (!$seller_fund_model->save(false)) {
                        \Yii::getLogger()->log($seller_fund_model->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('生成卖家资金错误！');
                    }
                }else{
                    $seller_fund->user_sum = $seller_fund->user_sum + $seller_in;
                    if (!$seller_fund->save(false)) {
                        \Yii::getLogger()->log($seller_fund->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('保存卖家资金错误！');
                    }
                }
                
                if($agent_uid != 0){
                    //代理人资金记录
                    $agent_fund_detail_model = new UserFundDetail();
                    $agent_fund_detail_model->userid = $region->agent_uid;
                    $agent_fund_detail_model->type = 3;
                    $agent_fund_detail_model->money = $agent_in;
                    $agent_fund_detail_model->goods_id = $order_goods['goods_id'];
                    $agent_fund_detail_model->order_no = $order_no;
                    $agent_fund_detail_model->name = '广告位区域代理分成--'.$money_type_string;
                    $agent_fund_detail_model->addtime = time();
                    if (!$agent_fund_detail_model->save(false)) {
                        \Yii::getLogger()->log($agent_fund_detail_model->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('生成充值记录错误！');
                    }
                    //代理人资金
                    $agent_fund = UserFund::findOne(['userid'=>$region->agent_uid]);
                    if(empty($agent_fund)){//没有资金记录的，创建资金记录
                        $agent_fund_model = new UserFund();
                        $agent_fund_model->userid = $region->agent_uid;
                        $agent_fund_model->user_sum = $agent_in;
                        $agent_fund_model->addtime = time();
                        if (!$agent_fund_model->save(false)) {
                            \Yii::getLogger()->log($agent_fund_model->errors, \yii\log\Logger::LEVEL_ERROR);
                            throw new \Exception('生成用户资金记录错误！');
                        }
                    }else{
                        $agent_fund->user_sum = $agent_fund->user_sum + $agent_in;
                        if (!$agent_fund->save(false)) {
                            \Yii::getLogger()->log($agent_fund->errors, \yii\log\Logger::LEVEL_ERROR);
                            throw new \Exception('保存用户资金错误！');
                        }
                    }
                }

                if($order->invitor_id !=0){
                    //合伙人资金记录
                    $partner_fund_detail_model = new UserFundDetail();
                    $partner_fund_detail_model->userid = $order->invitor_id;
                    $partner_fund_detail_model->type = 4;
                    $partner_fund_detail_model->money = $inviter_in;
                    $partner_fund_detail_model->goods_id = $order_goods['goods_id'];
                    $partner_fund_detail_model->order_no = $order_no;
                    $partner_fund_detail_model->name = '合伙人分成--'.$money_type_string;
                    $partner_fund_detail_model->addtime = time();
                    if (!$partner_fund_detail_model->save(false)) {
                        \Yii::getLogger()->log($partner_fund_detail_model->errors, \yii\log\Logger::LEVEL_ERROR);
                        throw new \Exception('生成充值记录错误！');
                    }
                    //合伙人资金
                    $partner_fund = UserFund::findOne(['userid'=>$order->invitor_id]);
                    if(empty($partner_fund)){//没有资金记录的，创建资金记录
                        $partner_fund_model = new UserFund();
                        $partner_fund_model->userid = $order->invitor_id;
                        $partner_fund_model->user_sum = $inviter_in;
                        $partner_fund_model->addtime = time();
                        if (!$partner_fund_model->save(false)) {
                            \Yii::getLogger()->log($partner_fund_model->errors, \yii\log\Logger::LEVEL_ERROR);
                            throw new \Exception('生成合伙人资金记录错误！');
                        }
                    }else{
                        $partner_fund->user_sum = $partner_fund->user_sum + $inviter_in;
                        if (!$partner_fund->save(false)) {
                            \Yii::getLogger()->log($partner_fund->errors, \yii\log\Logger::LEVEL_ERROR);
                            throw new \Exception('保存合伙人资金错误！');
                        }
                    }
                }
                
                //添加系统资金记录
                $sys_fund_detail_model = new SysFundDetail();
                $sys_fund_detail_model->type = 0;
                $sys_fund_detail_model->goods_id = $order_goods['goods_id'];
                $sys_fund_detail_model->money = $sys_in;
                $sys_fund_detail_model->order_no = $order_no;
                $sys_fund_detail_model->addtime = time();
                if (!$sys_fund_detail_model->save(false)) {
                    \Yii::getLogger()->log($sys_fund_detail_model->errors, \yii\log\Logger::LEVEL_ERROR);
                    throw new \Exception('生成系统资金记录错误！');
                }
                //更新系统资金
                $sys_fund_model = SysFund::findOne(1);//获取系统资金
                $sys_fund_model->sys_sum = $sys_fund_model->sys_sum + $sys_in;
                if (!$sys_fund_model->save(false)) {
                    \Yii::getLogger()->log($sys_fund_model->errors, \yii\log\Logger::LEVEL_ERROR);
                    throw new \Exception('更新系统资金记录错误！');
                }
                
                //更新订单商品的信息 交易完成
                $update_order_goods_nums = OrderGoods::updateAll(['status'=>4],['status'=>1,'order_no'=>$order_no]);
                if($update_order_goods_nums==0){
                    throw new \Exception('更新订单商品失败！');
                }
                
                //更新订单信息 交易完成
                $update_order_nums = Order::updateAll(['status'=>4],['status'=>1,'order_no'=>$order_no]);
                if($update_order_nums==0){
                    throw new \Exception('更新订单失败！');
                }
                
                $transaction->commit();
            } catch (\yii\db\Exception $e){
                $transaction->rollBack();
                return false;
            }
            return true;
        }
    }
    
    //订单列表数据
    public static function getOrderList($userid,$condition,$page_no){
        //获取符合条件的商品的个数
        $perpage = 15;
        $sql_condition_arr = [];
        array_push($sql_condition_arr,'buyer_id='.$userid);
        
        $sql_condition_string = implode(' and ', $sql_condition_arr);
        $data['total'] = self::getCountByCondition($sql_condition_string);
        $data['perpage'] = $perpage;
        $begin = $perpage*($page_no-1);
        $orderdata = self::getOrderByPage($sql_condition_string, $begin, $perpage);
        
        foreach ($orderdata as $order_key=>$order){//获取订单的商品
            $order['order_no'];//订单编号
            $order['status'];
            $order_disable = 0;
            $order_goods_list = OrderGoods::getOrderGoodsByOrderNo($order['order_no']);
            foreach($order_goods_list as $order_goods_key=>$order_goods){
                $packages = OrderGoodsPackage::getOrderGoodsPackage($order_goods['goods_no'], $order_goods['goods_id']);
                $order_goods_disable = 0;
                //未支付的订单 检测合法性
                if($order_goods['status']==0){
                    //不含套餐的订单商品
                    if($order_goods['have_package']==0){
                        $goods = Goods::findOne($order_goods['goods_id']);
                        
                        switch($order_goods['first_cate']){
                            case 1:
                                if($goods->order_endtime < time() || $goods->last_buyerid == $userid){
                                    //符合购买条件
                                }else{
                                    $order_disable = 1;
                                    $order_goods_disable = 1;
                                }
                                break;
                            case 7:
                                if($goods->nums >= $order_goods['nums']){
                                    //符合条件
                                }else{
                                    $order_disable = 1;
                                    $order_goods_disable = 1;
                                }
                                break;
                            default :
                        }
                        
                    }
                    
                    //含有套餐的，检测套餐
                    if(!empty($packages)){
                        foreach($packages as $package_key=>$package){
                            $package_disable = 0;
                            $goods_package = GoodsPackage::findOne($package['package_id']);
                            switch($package['first_cate']){
                                case 1:
                                    if($goods_package->buy_able_time < $package['begin_time'] || $goods_package->last_buyerid == $userid){
                                        //符合购买条件
                                    }else{
                                        $order_disable = 1;
                                        $order_goods_disable = 1;
                                        $package_disable = 1;
                                    }
                                    break;
                                case 7:
                                    if($goods->nums >= $order_goods['nums']){
                                        //符合条件
                                    }else{
                                        $order_disable = 1;
                                        $order_goods_disable = 1;
                                        $package_disable = 1;
                                    }
                                    break;
                                default :
                            }
                            
                            $packages[$package_key]['disable'] = $package_disable;
                        }
                    }
                }
                
                $order_goods_list[$order_goods_key]['packages'] = $packages;
                
                $order_goods_list[$order_goods_key]['img'] = GoodsImg::getDefaultGoodsimgByGoodsno($order_goods['goods_no']);//获取订单商品的默认图片
                
                $order_goods_list[$order_goods_key]['disable'] = $order_goods_disable;
                
            }
            $orderdata[$order_key]['disable'] = $order_disable;
            $orderdata[$order_key]['order_goods_list'] = $order_goods_list;
        }
        
        $data['orderdata'] = $orderdata;
        
        return $data;
    }
    //获取订单数量
    public static function getCountByCondition($sql_condition_string){
        $sql = "select count(id) total from `order` where $sql_condition_string";
        $command = \Yii::$app->db->createCommand($sql);
    	$model = $command->queryOne();
        return $model['total'];
    }
    
    //获取分页订单数据
    public static function getOrderByPage($sql_condition_string, $begin, $perpage){
        $sql = "select * from `order` where $sql_condition_string order by id desc limit $begin,$perpage";
        $command = \Yii::$app->db->createCommand($sql);
    	return $model = $command->queryAll();
    }
}
